//
//  ActivityDetailViewController.m
//  WindRunner
//
//  Created by leeqb on 12/4/14.
//  Copyright (c) 2014 poweropt. All rights reserved.
//

#import "ActivityDetailViewController.h"
#import "ActivityEditViewController.h"
#import "ActivityMemberViewController.h"

@interface ActivityDetailViewController ()
{
    NSInteger _memberStatus;
    NSInteger _joinStatus;
    NSInteger _barOperType;
}
@end

@implementation ActivityDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _barOperType = 1;
    
    self.appleNavButton.layer.cornerRadius = 4;
    self.appleNavButton.layer.masksToBounds = YES;
    
    self.joinButton.layer.cornerRadius = 4;
    self.joinButton.layer.masksToBounds = YES;
    
    self.deleteButton.layer.cornerRadius = 4;
    self.deleteButton.layer.masksToBounds = YES;
    self.deleteButton.hidden = YES;
    
    CGRect rect = _footerView.frame;
    rect.size.height = 60;
    _footerView.frame = rect;
    _activityTable.tableFooterView = _footerView;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.title = LocalStringEvent(@"NAV_TITLE_ACTIVITY_DETAIL");
    
    _nameLabel.text = [NSString formatString:self.data[@"title"]];
    _locationLabel.text = [NSString formatString:self.data[@"location"]];
    _limitsLabel.text = [NSString formatString:self.data[@"personcount"]];
    //_remindLabel.text = [NSString formatString:self.data[@"warntime"]];
    _requireLabel.text = [NSString formatString:self.data[@"slogan"]];
    
    NSString *actType = [NSString formatString:self.data[@"type"]];
    if([actType isEqualToString:@""] || [actType isEqualToString:@"-1"]) {
        actType = @"0";
    }
    _typeLabel.text = [ActivityEditViewController getActivityTypes][[actType integerValue]];
    
    NSString *startTimeString = [NSString formatString:self.data[@"starttime"]];
    NSString *endTimeString = [NSString formatString:self.data[@"endtime"]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"MM-dd HH:mm";
    if(![startTimeString isEqualToString:@""]) {
        NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:[startTimeString doubleValue]/1000];
        _timeLabel.text = [dateFormatter stringFromDate:startDate];
    }
    
    if(![endTimeString isEqualToString:@""]) {
        NSDate *endDate = [NSDate dateWithTimeIntervalSince1970:[endTimeString doubleValue]/1000];
        _endTimeLabel.text = [dateFormatter stringFromDate:endDate];
    }
    
    _activityImageView.image = [UIImage imageNamed:@"circle_detail_top_bg"];
    NSString *imageUrl = [NSString formatString:self.data[@"imgurl"]];
    //imageUrl = [NSString stringWithFormat:@"%@%@", IMAGE_URL_PREFIX, imageUrl];
    LEDownloadManager *downloader = [[LEDownloadManager alloc] initWithTarget:_activityImageView];
    [downloader downLoadImageWithURL:imageUrl imagetype:@"ActivityDetailImages"];
    
    _memberStatus = [[NSString formatString:self.data[@"memberstatus"]] integerValue];
    _joinStatus = [[NSString formatString:self.data[@"joinstatus"]] integerValue];
    NSString *createrString = [NSString formatString:self.data[@"creater"]];
    if([[AuthHelper getCurrentUser][@"id"] longLongValue] == [createrString longLongValue]) { // 创建人显示管理成员
        _barOperType = 2;
        [_joinButton setTitle:LocalStringEvent(@"ADETAIL_BTN_CREATER") forState:UIControlStateNormal];
        
        UIImage *editImage = [UIImage imageNamed:@"ic_edit.png"];
        [_rightBarButton setImage:editImage
                         forState:UIControlStateNormal];
        CGRect rect = _rightBarButton.frame;
        rect.size.width = editImage.size.width / 2.7;
        rect.size.height = editImage.size.height / 2.7;
        _rightBarButton.frame = rect;
        _rightBarButton.contentEdgeInsets = UIEdgeInsetsMake(0, 6, 0, -6);
    } else {
        if(_memberStatus == 1) { // 已加入
            _joinButton.enabled = NO;
            [_joinButton setTitle:LocalStringEvent(@"ADETAIL_BTN_JOINED") forState:UIControlStateDisabled];
        } else { // 未加入
            if(_joinStatus == 1) { // 已申请
                _joinButton.enabled = NO;
                [_joinButton setTitle:LocalStringEvent(@"ADETAIL_BTN_APPLYED") forState:UIControlStateDisabled];
            } else { // 未申请
                [_joinButton setTitle:LocalStringEvent(@"ADETAIL_BTN_NOTAPPLY") forState:UIControlStateNormal];
            }
        }
    }
    
    if([[AuthHelper getCurrentUser][@"id"] integerValue] ==
       [[NSString formatString:self.data[@"creater"]] integerValue]) {
        _deleteButton.hidden = NO;
        [_deleteButton setTitle:LocalStringEvent(@"ADETAIL_BTN_DELETE") forState:UIControlStateNormal];
        CGRect rect = _footerView.frame;
        rect.size.height = 100;
        _footerView.frame = rect;
        _activityTable.tableFooterView = _footerView;
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"segActDetailToEdit"]) {
        ActivityEditViewController *vc = (ActivityEditViewController *)segue.destinationViewController;
        vc.data = self.data;
    } else if([[segue identifier] isEqualToString:@"segActivityMembers"]) {
        ActivityMemberViewController *vc = (ActivityMemberViewController *)segue.destinationViewController;
        vc.data = self.data;
    }
}
    
- (IBAction)joinButtonClicked:(UIButton *)sender {
    NSString *createrString = [NSString formatString:self.data[@"creater"]];
    if([[AuthHelper getCurrentUser][@"id"] longLongValue] == [createrString longLongValue]) { // 创建人显示管理成员
        [self performSegueWithIdentifier:@"segActivityMembers" sender:nil];
    } else {
        if(_joinStatus == 0) {
            NSDictionary *requestData = @{@"activityid":self.data[@"id"],
                                          @"userid":[AuthHelper getCurrentUser][@"id"]};
            FMRequestObject *requestObj = [[FMRequestObject alloc] initWithRUL:BASE_API_URL_WINDRUNNER
                                                                     interface:@"activeapply"
                                                                        params:requestData];
            [FMNetwork request:requestObj showMask:YES success:^(NSDictionary *data) {
                [FMToast showMessage:@"申请成功"];
                [_joinButton setTitle:@"已申请" forState:UIControlStateNormal];
            } falied:^(NSError *error) {
            }];
        }
    }
}

- (IBAction)rightBarClicked:(UIButton *)sender {
    if(_barOperType == 1) {
        
    } else if(_barOperType == 2) {
        [self performSegueWithIdentifier:@"segActDetailToEdit" sender:nil];
    }
}

- (IBAction)deleteButtonClick:(UIButton *)sender {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil
                                                        message:LocalStringEvent(@"CDETAIL_CONFIRM_DELETE")
                                                       delegate:self
                                              cancelButtonTitle:LocalStringCommon(@"ALERT_CANCEL")
                                              otherButtonTitles:LocalStringCommon(@"ALERT_OK"), nil];
    [alertView show];
}

- (IBAction)navBaidu:(id)sender {
    CLLocationCoordinate2D endCoor;
    endCoor.longitude = [self.data[@"locationX"] doubleValue];
    endCoor.latitude = [self.data[@"locationY"] doubleValue];
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:endCoor addressDictionary:nil];
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:placemark];
    toLocation.name = [NSString formatString:self.data[@"location"]];
    
    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                   launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
}

- (IBAction)navGG:(id)sender {
    NSString *urlString = [NSString stringWithFormat:@"http://www.google.com/maps?saddr=%@,%@&daddr=%@,%@", CURR_COORDINATE_Y_STR, CURR_COORDINATE_X_STR, self.data[@"locationY"], self.data[@"locationX"]];
    NSURL *url = [NSURL URLWithString:urlString];
    if([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1) {
        NSDictionary *requestData = @{@"userid":[AuthHelper getCurrentUser][@"id"],
                                      @"activityid":self.data[@"id"]};
        FMRequestObject *requestObj = [[FMRequestObject alloc] initWithRUL:BASE_API_URL_WINDRUNNER
                                                                 interface:@"activitydelete"
                                                                    params:requestData];
        [FMNetwork request:requestObj showMask:YES success:^(NSDictionary *data) {
            [FMToast showMessage:LocalStringCommon(@"DEL_SUCC")];
            [_eventContoller removeActivity:self.data];
            [self.navigationController popViewControllerAnimated:YES];
        } falied:^(NSError *error) {
            [FMToast showMessage:LocalStringCommon(@"DEL_FAIL")];
        }];
    }
}

@end
